//
//  ChatHelper.m
//  ZPrograme
//
//  Created by 周成龙 on 16/6/19.
//  Copyright © 2016年 none. All rights reserved.
//

#import "ChatHelper.h"

#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "VDJConstant.h"
#import "ChatPalySoundHelper.h"
#import "TabBarVC.h"
#import "ZNavigationController.h"

#import "ZAlertControlTool.h"


static ChatHelper *helper = nil;
@implementation ChatHelper

+ (instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[ChatHelper alloc] init];
    });
    return helper;
}

- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initHelper];
    }
    return self;
}

- (void)initHelper
{
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}

// 从服务器获取推送属性
- (void)asyncPushOptions
{
    [[EMClient sharedClient] asyncGetPushOptionsFromServer:nil failure:nil];
}

#pragma mark - EMClientDelegate

// 网络状态变化回调
//- (void)didConnectionStateChanged:(EMConnectionState)connectionState
//{
//    [self.mainVC networkChanged:connectionState];
//}

- (void)didAutoLoginWithError:(EMError *)error
{
    if([[EMClient sharedClient] isConnected]){
        [kAppdalegate login];
    }else {
        [kAppdalegate notLogin];
    }
}

// 当前登录账号在其它设备登录时会接收到该回调
- (void)didLoginFromOtherDevice
{
    [ZAlertControlTool showAlertControllerPreferredStyle:UIAlertControllerStyleAlert withTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"loginAtOtherDevice", @"your login account has been in other places") okTitle:NSLocalizedString(@"ok", @"OK") destructiveTitle:nil cancelTitle:nil okAction:^(UIAlertAction *action) {
        
        [self _clearHelper];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    } cancelAction:nil destructiveAction:nil];
}

// 当前登录账号已经被从服务器端删除时会收到该回调
- (void)didRemovedFromServer
{
    [ZAlertControlTool showAlertControllerPreferredStyle:UIAlertControllerStyleAlert withTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"loginUserRemoveFromServer", @"your account has been removed from the server side") okTitle:NSLocalizedString(@"ok", @"OK") destructiveTitle:nil cancelTitle:nil okAction:^(UIAlertAction *action) {
        
        [self _clearHelper];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    } cancelAction:nil destructiveAction:nil];
}

#pragma mark - EMChatManagerDelegate

// 会话列表发生变化
- (void)didUpdateConversationList:(NSArray *)aConversationList
{
//    if (self.mainVC) {
//        [_mainVC setupUnreadMessageCount];
//    }
//    
//    if (self.conversationListVC) {
//        [_conversationListVC refreshDataSource];
//    }
}

//收到消息
- (void)didReceiveMessages:(NSArray *)aMessages
{
    BOOL isRefreshCons = YES;
    for(EMMessage *message in aMessages){
        BOOL needShowNotification = (message.chatType != EMChatTypeChat) ? [self _needShowNotification:message.conversationId] : YES;
        
        if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
            ChatPalySoundHelper *playSound = [[ChatPalySoundHelper alloc] init];
            UIApplicationState state = [[UIApplication sharedApplication] applicationState];
            switch (state) {
                case UIApplicationStateActive:
                    [playSound playSoundAndVibration];
                    break;
                case UIApplicationStateInactive:
                    [playSound playSoundAndVibration];
                    break;
                case UIApplicationStateBackground:
                    [playSound showNotificationWithMessage:message];
                    break;
                default:
                    break;
            }
#endif
        }
        
        if (_chatVC == nil) {
            _chatVC = [self _getCurrentChatView];
        }
        BOOL isChatting = NO;
        if (_chatVC) {
            isChatting = [message.conversationId isEqualToString:_chatVC.conversation.conversationId];
        }
        if (_chatVC == nil || !isChatting) {
//            if (self.conversationListVC) {
//                [_conversationListVC refresh];
//            }
//            
//            if (self.mainVC) {
//                [_mainVC setupUnreadMessageCount];
//            }
            return;
        }
        
        if (isChatting) {
            isRefreshCons = NO;
        }
    }
    
    if (isRefreshCons) {
//        if (self.conversationListVC) {
//            [_conversationListVC refresh];
//        }
//        
//        if (self.mainVC) {
//            [_mainVC setupUnreadMessageCount];
//        }
    }
}

#pragma mark - EMGroupManagerDelegate
#pragma mark - EMContactManagerDelegate
#pragma mark - EMChatroomManagerDelegate
#pragma mark - EMCallManagerDelegate
#pragma mark - public

#pragma mark - private
- (BOOL)_needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EMClient sharedClient].groupManager getAllIgnoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    return ret;
}

- (ChatViewController*)_getCurrentChatView
{
    AppDelegate *app = kAppdalegate;
    UIWindow *window = app.window;
    TabBarVC *tabVC = (TabBarVC *)window.rootViewController;
    ZNavigationController *nav = (ZNavigationController *)tabVC.viewControllers[0];
    
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:nav.viewControllers];
    ChatViewController *chatViewContrller = nil;
    for (id viewController in viewControllers)
    {
        if ([viewController isKindOfClass:[ChatViewController class]])
        {
            chatViewContrller = viewController;
            break;
        }
    }
    return chatViewContrller;
}

- (void)_clearHelper
{
    self.chatVC = nil;
    [kAppdalegate removeUserInfo];
}


@end
